#include "db_client.h"
#include <QDebug>
#include <QMessageBox>
#include <QSqlRecord>
#include "log/log_init.h"
DBClient::DBClient()
{

}

bool DBClient::Connect(QString ip, QString port, QString user, QString pwd)
{
    dbClient =  QSqlDatabase::addDatabase("QMYSQL");
    dbClient.setHostName(ip);
    dbClient.setPort(port.toInt());
    dbClient.setDatabaseName("sosplus");       //这里输入你的数据库名
    dbClient.setUserName(user);
    dbClient.setPassword(pwd);   //这里输入你的密码
    if (!dbClient.open()) {
        QLOG_ERROR()<<__FUNCTION__ <<"db connect error "<<"ip :"<<ip<<"port :"<<port<<"user :"<<user<<"pwd :"<<pwd;
        QMessageBox::critical(NULL, "error ", "database connect error", QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
    }else{
        QLOG_INFO()<<__FUNCTION__ <<"connect sucess";
    }
    query = new QSqlQuery(dbClient);
    return true;
}

QList<DeptNode> DBClient::selectDeptQuery(QString sql)
{
    QList<DeptNode> ret;
    query->exec(sql);
    while(query->next()){
        DeptNode node;
        node.deptid = query->value("dept_id").toInt();
        node.parentid = query->value("dept_parent_id").toInt();
        node.deptname = query->value("dept_name").toString().toUtf8();
        node.deptorderid = query->value("dept_order_id").toInt();
        ret.append(node);
    }
    return ret;
}

QMap<QString, QString> DBClient::selectLoginQuery(QString sql)
{
    QMap<QString, QString> ret;
    query->exec(sql);

    while(query->next()){
        if(query->size()<2)
            continue;
        ret[query->value("user_login").toString()] = query->value("user_pwd").toString();
    }
    return ret;
}

QList<QList<QString> > DBClient::select(QString sql)
{
    QList<QList<QString> > ret;
    query->exec(sql);
    QSqlRecord rec = query->record();//获取有多少列
    while(query->next()){
        QList<QString> info;
        for(uint8_t i =0 ;i < rec.count() ;i++){
            info.append(query->value(i).toString());
        }
        ret.append(info);
    }
    return ret;
}

QSqlDatabase DBClient::getDataDBClient()
{
    return dbClient;
}
